﻿@model EquipmentListModel

@using Nop.Services.Security

@Html.HiddenFor(model => model.SearchCategoryId)

@{
    var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    var permissionService = EngineContext.Current.Resolve<IPermissionService>();
    var canManageEquipmentsEdit = permissionService.Authorize(StandardPermissionProvider.ManageEquipmentsEdit);

    //page title
    ViewBag.Title = "库存管理";
    //active menu item (system name)
    Html.SetActiveMenuItemSystemName("Consumables list");
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <style type="text/css">
        #treeView .k-group {
            min-width: 200px;
        }
    </style>
    <script id="template" type="text/x-kendo-template">
    @{ if (canManageEquipmentsEdit)
        {
            <a href="javascript:add();" class="btn bg-blue k-button k-button-md k-rounded-md k-button-solid k-button-solid-base">
                <i class="fa fa-plus-square"></i>
                @T("Admin.Common.AddNew")
            </a>
        }
    }
    </script>
    <div class="content-header clearfix">
        <h1 class="pull-left">
            库存管理
        </h1>
        <div class="pull-right">
            <button type="submit" name="exportexcel-all" class="btn bg-olive">
                <i class="fa fa-download"></i>
                @T("Admin.Common.Export")
            </button>
            <button type="button" name="importexcel" class="btn bg-olive" data-toggle="modal" data-target="#importexcel-window">
                <i class="fa fa-upload"></i>
                @T("Admin.Common.Import")
            </button>
        </div>
    </div>
    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <div class="col-md-2 col-search">
                                        <div class="label-wrapper"><label class="control-label" for="SearchName" title="">名称</label></div>
                                        <div class="col-content">
                                            @Html.NopEditorFor(model => model.SearchName)
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-search">
                                        <div class="label-wrapper"><label class="control-label" for="SearchManufacturer" title="">品牌</label></div>
                                        <div class="col-content">
                                            @Html.NopEditorFor(model => model.SearchManufacturer)
                                        </div>
                                    </div>
                                    <div class="col-md-2 col-search">
                                        <div class="label-wrapper"><label class="control-label" for="SearchSpecification" title="">规格型号</label></div>
                                        <div class="col-content">
                                            @Html.NopEditorFor(model => model.SearchSpecification)
                                        </div>
                                    </div>
                                    <div class="col-md-1 col-search">
                                        <div class="label-wrapper col-flex2"><label class="control-label" for="OnlyStock" title="">有库存</label></div>
                                        <div class="col-flex1">
                                            @Html.NopEditorFor(model => model.OnlyStock)
                                        </div>
                                    </div>
                                    <div class="col-md-1 col-search">
                                        <div class="label-wrapper col-flex2"><label class="control-label" for="OnlyWarn" title="">库存预警</label></div>
                                        <div class="col-flex1">
                                            @Html.NopEditorFor(model => model.OnlyWarn)
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <button type="button" id="search-categories" class="btn btn-primary"><i class="fa fa-search"></i>@T("Admin.Common.Search")</button>
                                        <button type="button" id="cancel-categories" class="btn btn-default"><i class="fa fa-refresh"></i>重置</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <div class="col-md-2">
                                        <div id="treeView"></div>
                                        <input type="submit" id="btnRefreshTree" style="display: none" />
                                    </div>
                                    <div class="col-md-10">
                                        <div id="categories-grid"></div>
                                        <input type="submit" id="btnRefreshGrid" style="display: none" />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <style type="text/css">
                            .li i {
                                display: none;
                            }

                            .li:hover i {
                                display: inline-block;
                            }

                            .fabtn {
                                padding-left: 5px;
                                font-size: 16px;
                            }

                            .stock {
                                cursor: pointer;
                                text-decoration: underline;
                            }

                            .warning {
                                color: red;
                            }
                        </style>
                        <script>

                    $(document).ready(function () {
                        $("#treeView").kendoTreeView({
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("Tree", "EquipmentCategory"))",
                                        type: "POST",
                                        dataType: "json",
                                        data: additionalTreeData
                                    }
                                },
                                schema: {
                                    model: {
                                        id: "id",
                                        children: "items"
                                    }
                                }
                            },
                            //dataTextField: 'name'
                            template: function (dataItem) {
                                if (@(canManageEquipmentsEdit?1:0)== 0)
                                    return `<div id="${dataItem.item.id}" class="li"><span id="text${dataItem.item.id}">${dataItem.item.text}</span></div>`;
                                if (dataItem.item.id === 0)
                                    return `<div id="${dataItem.item.id}" class="li"><span id="text${dataItem.item.id}">${dataItem.item.text}</span>&nbsp;&nbsp;<i data-id="${dataItem.item.id}" data-type="add" class="fa fa-plus-square" title="新增子节点"></i></div>`;
                                if (dataItem.item.addable) {
                                    return `<div id="${dataItem.item.id}" class="li"><span id="text${dataItem.item.id}">${dataItem.item.text}</span>&nbsp;&nbsp;<i data-id="${dataItem.item.id}" data-type="add" class="fa fa-plus-square" title="新增子节点"></i>&nbsp;&nbsp;<i data-id="${dataItem.item.id}" data-type="edit" class="fa fa-pencil-square" title="编辑"></i>&nbsp;&nbsp;<i data-id="${dataItem.item.id}" data-type="delete" class="fa fa-trash" title="删除"></i></div>`;
                                }
                                return `<div id="${dataItem.item.id}" class="li"><span id="text${dataItem.item.id}">${dataItem.item.text}</span>&nbsp;&nbsp;<i data-id="${dataItem.item.id}" data-type="edit" class="fa fa-pencil-square" title="编辑"></i>&nbsp;&nbsp;<i data-id="${dataItem.item.id}" data-type="delete" class="fa fa-trash" title="删除"></i></div>`;
                            },
                            select(e) {
                                const li = $(e.node).find('.li')[0];
                                if (li) {
                                    $('#@Html.FieldIdFor(model => model.SearchCategoryId)').val(li.id);
                                    $("#search-categories").click();
                                }
                                return false;
                            },
                            expand: function (e) {
                                return false;
                            }
                        });

                        $("#treeView").on("click", "i.fa", function (e) {
                            if (e.target.dataset.type === 'add') {
                                OpenWindow('@(Url.Action("AddPopup", "EquipmentCategory"))?pId=' + e.target.dataset.id +'&isConsumables=true&btnId=btnRefreshTree', 1000, 800, true)
                            }
                            if (e.target.dataset.type === 'edit') {
                                OpenWindow('@(Url.Action("EditPopup", "EquipmentCategory"))/' + e.target.dataset.id +'?isConsumables=true&btnId=btnRefreshTree', 1000, 800, true)
                            }
                            if (e.target.dataset.type === 'delete') {
                                if (confirm('@T("Admin.Common.AreYouSure")')) {
                                    var postData = {
                                        id: e.target.dataset.id
                                    };
                                    addAntiForgeryToken(postData);

                                    $.ajax({
                                        cache: false,
                                        type: 'POST',
                                        url: '@Url.Action("CategoryDelete", "EquipmentCategory")',
                                        data: postData,
                                        dataType: 'json',
                                        success: function (data) {
                                            //refresh grid
                                            /*$('#btnRefreshTree').click();*/
                                            if (data.result) {
                                                //删除指定节点
                                                var tree = $("#treeView").data('kendoTreeView');
                                                tree.remove(e.currentTarget);
                                            }
                                            return false;
                                        },
                                        error: function(xhr, ajaxOptions, thrownError) {
                                            alert('Failed to delete');
                                        }
                                    });
                                }
                            }
                            return false;
                        });

                        $('#btnRefreshTree').click(function (a) {
                            //refresh grid
                            var tree = $("#treeView").data('kendoTreeView');
                            tree.dataSource.read();

                            //return false to don't reload a page
                            return false;
                        });

                        var columns = [
                            {
                                field: "Name",
                                title: "名称",
                                width: 300,
                                headerAttributes: { style: "text-align:center" },
                                template: '# if(CategoryMainId===1) {# <i class="fa fa-university true-icon-min" title="耗材"></i> #} else {# <i class="fa fa-gears false-icon-min" title="配件"></i> #} if(Published) {# <span>#=Name#</span> #} else {# <span style="opacity: 0.5;" title="未发布">#=Name#</span> #}#'
                            }, {
                                field: "Manufacturer",
                                title: "品牌",
                                width: 200,
                                headerAttributes: { style: "text-align:center" },
                            }, {
                                field: "Specification",
                                title: "规格型号",
                                width: 300,
                                headerAttributes: { style: "text-align:center" },
                            }, {
                                field: "Unit",
                                title: "单位",
                                width: 60,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                            }, {
                                field: "Price",
                                title: "单价",
                                width: 100,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:right" },
                            }, {
                                field: "Stock",
                                title: "当前库存",
                                width: 100,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '# if(StockMin>0&&StockMin>=Stock) {# <span onclick="javascript: showStockLog(#=Id#);" title="最低库存：#=StockMin#" class="stock warning">#=Stock#</span> #} else {# <span onclick="javascript: showStockLog(#=Id#);" class="stock">#=Stock#</span> #} #',
                                //footerTemplate:'<span style="float:right">#=sum#</span>'
                            }, {
                                field: "Freeze",
                                title: "领用申请",
                                width: 100,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '<span onclick="javascript: showStockOutDetail(#=Id#);" class="stock">#=Freeze#</span>'
                            },
                        ];
                        if (@(canManageEquipmentsEdit?1:0)== 1) {
                            columns.push({
                                field: "Id",
                                title: "操作",
                                width: 120,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '<i class="fa fabtn fa-pencil fa-active" title="编辑" onclick="javascript: OpenWindow(\'@(Url.Action("EditPopup", "Consumables"))/#=Id#?btnId=btnRefreshGrid\', 1000, 800, true);return false;"></i><i class="fa fabtn fa-trash fa-active" title="删除" onclick="javascript: delEquipment(#=Id#);"></i>',
                            });
                        }
                        $("#categories-grid").kendoGrid({
                            toolbar: [
                                { template: kendo.template($("#template").html()) }
                            ],
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("ConsumablesList", "Consumables"))",
                                        type: "POST",
                                        dataType: "json",
                                        data: additionalData
                                    }
                                },
                                schema: {
                                    data: "Data",
                                    total: "Total",
                                    errors: "Errors",
                                    model: {
                                        fields: {
                                            ProductionDate: {type:"date"},
                                            Stock: { type: "number" }
                                        }
                                    }
                                },
                                error: function(e) {
                                    display_kendoui_grid_error(e);
                                    // Cancel the changes
                                    this.cancelChanges();
                                },
                                pageSize: @(defaultGridPageSize),
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true,
                                //aggregate: [
                                //    { field: "Stock", aggregate: "sum" },
                                //    { field: "Freeze", aggregate: "sum" }
                                //]
                            },
                            pageable: {
                                refresh: true,
                                pageSizes: [@(gridPageSizes)],
                                @Html.Partial("_GridPagerMessages")
                            },
                            editable: {
                                confirmation: "@T("Admin.Common.DeleteConfirmation")",
                                mode: "inline"
                            },
                            scrollable: false,
                            columns: columns,
                        });

                        $('#btnRefreshGrid').click(function () {
                            //refresh grid
                            var grid = $("#categories-grid").data('kendoGrid');
                            grid.dataSource.read();

                            //return false to don't reload a page
                            return false;
                        });
                    });
                        function refreshNode(e) {
                            $('#text' + e.id).text(e.text);
                        }
                        function addNode(e) {
                            var treeView = $("#treeView").data("kendoTreeView");
                            var dataSource = treeView.dataSource.data(); // 获取当前数据源数组
                            addChild(dataSource, e);
                            //treeView.refresh();
                            //console.log(dataSource,e);
                            //// 创建一个新节点对象
                            //var newNode = {
                            //    text: e.text,
                            //    id: e.id
                            //};

                            //// 将新节点添加到数据源数组中
                            //dataSource.push(newNode);

                            // 刷新树视图以显示新节点
                            //treeView.dataSource.read(); // 或者 treeView.refresh();
                        }
                            function addChild(items, e) {
                            items.map(m => {
                                if (e.pid === m.id) {
                                    m.items.push({
                                        text: e.text,
                                        id: e.id,
                                        items: [],
                                        addable: e.pid == 0,
                                        expanded: true,
                                    })
                                }
                                else {
                                    if (m.items) {
                                        addChild(m.items, e)
                                    }
                                }
                            })
                        }
                        </script>

                        <script type="text/javascript">
                        $(document).ready(function() {
                            //search button
                            $('#search-categories').click(function() {
                                //search
                                var grid = $('#categories-grid').data('kendoGrid');
                                grid.dataSource.page(1); //new search. Set page size to 1
                                //grid.dataSource.read(); we already loaded the grid above using "page" function
                                return false;
                            });
                            //cancel button
                            $('#cancel-categories').click(function () {
                                //cancel
                                var grid = $('#categories-grid').data('kendoGrid');
                                $('#@Html.FieldIdFor(model => model.SearchCategoryId)').val('0');
                                $('#@Html.FieldIdFor(model => model.SearchName)').val('');
                                $('#@Html.FieldIdFor(model => model.SearchManufacturer)').val('');
                                $('#@Html.FieldIdFor(model => model.SearchSpecification)').val('');
                                $('#@Html.FieldIdFor(model => model.OnlyStock)').prop('checked', false);
                                $('#@Html.FieldIdFor(model => model.OnlyWarn)').prop('checked', false);
                                grid.dataSource.page(1); //new search. Set page size to 1
                                //grid.dataSource.read(); we already loaded the grid above using "page" function

                                //refresh grid
                                var tree = $("#treeView").data('kendoTreeView');
                                tree.dataSource.read();
                                return false;
                            });

                            $("#@Html.FieldIdFor(model => model.SearchName)").keydown(function(event) {
                                if (event.keyCode == 13) {
                                    $("#search-categories").click();
                                    return false;
                                }
                            });

                            $("#@Html.FieldIdFor(model => model.SearchManufacturer)").keydown(function(event) {
                                if (event.keyCode == 13) {
                                    $("#search-categories").click();
                                    return false;
                                }
                            });

                            $("#@Html.FieldIdFor(model => model.SearchSpecification)").keydown(function(event) {
                                if (event.keyCode == 13) {
                                    $("#search-categories").click();
                                    return false;
                                }
                            });
                        });

                        function additionalData() {
                            var data = {
                                SearchCategoryId: $('#@Html.FieldIdFor(model => model.SearchCategoryId)').val(),
                                SearchName: $('#@Html.FieldIdFor(model => model.SearchName)').val(),
                                SearchManufacturer: $('#@Html.FieldIdFor(model => model.SearchManufacturer)').val(),
                                SearchSpecification: $('#@Html.FieldIdFor(model => model.SearchSpecification)').val(),
                                OnlyStock: $('#@Html.FieldIdFor(model => model.OnlyStock)').is(':checked'),
                                OnlyWarn: $('#@Html.FieldIdFor(model => model.OnlyWarn)').is(':checked'),
                            };
                            addAntiForgeryToken(data);
                            return data;
                        }

                        function additionalTreeData() {
                            var data = {
                                isConsumables: true,
                            };
                            addAntiForgeryToken(data);
                            return data;
                        }

                        function add() {
                            const cId = $('#@Html.FieldIdFor(model => model.SearchCategoryId)').val();
                            OpenWindow('@(Url.Action("AddPopup", "Consumables"))?cId=' + cId + '&btnId=btnRefreshGrid', 1000, 800, true);
                        }

                        function delEquipment(id) {
                            if (confirm('@T("Admin.Common.AreYouSure")')) {
                                var postData = {
                                    id
                                };
                                addAntiForgeryToken(postData);

                                $.ajax({
                                    cache: false,
                                    type: 'POST',
                                    url: '@Url.Action("ConsumablesDelete", "Consumables")',
                                    data: postData,
                                    dataType: 'json',
                                    success: function (data) {
                                        if (data.result) {
                                            //refresh grid
                                            $('#btnRefreshGrid').click();
                                        }
                                        else {
                                            alert(data.msg);
                                        }
                                        return false;
                                    },
                                    error: function(xhr, ajaxOptions, thrownError) {
                                        alert('Failed to delete');
                                    }
                                });
                            }
                        }

                        function addStockIn(id) {
                            OpenWindow('@(Url.Action("InPopup", "EquipmentStockLog"))?eId=' + id + '&btnId=btnRefreshGrid', 1000, 800, true);
                        }

                        function addStockOut(id) {
                            OpenWindow('@(Url.Action("OutPopup", "EquipmentStockLog"))?eId=' + id + '&btnId=btnRefreshGrid', 1000, 800, true);
                        }

                        function showStockLog(id) {
                            const w = $('.content-wrapper .content').eq(0).width();
                            if (w > 0) {
                                OpenWindow('@(Url.Action("LogPopup", "EquipmentStockLog"))?eId=' + id + '&btnId=btnRefreshGrid', w, 800, true);
                            }
                            else {
                                OpenWindow('@(Url.Action("LogPopup", "EquipmentStockLog"))?eId=' + id + '&btnId=btnRefreshGrid', window.innerWidth, 800, true);
                            }
                        }

                        function showStockOutDetail(id) {
                            const w = $('.content-wrapper .content').eq(0).width();
                            if (w > 0) {
                                OpenWindow('@(Url.Action("DetailPopup", "EquipmentStockOut"))?eId=' + id + '&btnId=btnRefreshGrid', w, 800, true);
                            }
                            else {
                                OpenWindow('@(Url.Action("DetailPopup", "EquipmentStockOut"))?eId=' + id + '&btnId=btnRefreshGrid', window.innerWidth, 800, true);
                            }
                        }

                        function showStock(id)   {
                            const w = $('.content-wrapper .content').eq(0).width();
                            if (w > 0) {
                                OpenWindow('@(Url.Action("Popup", "EquipmentStock"))?eId=' + id + '&btnId=btnRefreshGrid', w, 800, true);
                            }
                            else {
                                OpenWindow('@(Url.Action("Popup", "EquipmentStock"))?eId=' + id + '&btnId=btnRefreshGrid', window.innerWidth, 800, true);
                            }
                        }
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
}

@*import categories form*@
<div id="importexcel-window" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="importexcel-window-title">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="importexcel-window-title">@T("Admin.Common.ImportFromExcel")</h4>
            </div>
            @using (Html.BeginForm("ImportFromXlsx", "Consumables", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <div class="form-horizontal">
                    <div class="modal-body">
                        @Html.AntiForgeryToken()
                        <ul class="common-list">
                            <li>
                                <em>导入需要大量的内存资源。这就是为什么不建议一次导入超过 500 至 1000 条记录。如果您有更多记录，最好将其拆分到多个 Excel 文件中，然后分别导入。</em>
                            </li>
                        </ul>
                        <div class="form-group">
                            <div class="col-md-2">
                                <div class="label-wrapper">
                                    <label class="control-label">
                                        @T("Admin.Common.ExcelFile")
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-10">
                                <input type="file" id="importexcelfile" name="importexcelfile" class="form-control" />
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">
                            @T("Admin.Common.ImportFromExcel")
                        </button>
                    </div>
                </div>
            }
        </div>
    </div>
</div>